package com.yami.shop.api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.pt.YxPtsp;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.IYxPtspService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.ShopDetailService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/shop/shop")
public class ShopController {

    @Autowired
    private ShopDetailService shopService;

    @Autowired
    private ProductService productService;

    @Autowired
    private IYxPtspService yxPtspService;

    /**
     * 获取信息
     */
    @GetMapping("/info")
    @PreAuthorize("@pms.hasPermission('shop:shop:info')")
    public ResponseEntity<ShopDetail> info() {
        ShopDetail shopDetail = shopService.getShopDetailByShopId(SecurityUtils.getSysUser().getShopId());
        return ResponseEntity.ok(shopDetail);
    }

    @GetMapping("/page")
    public ResponseEntity<IPage<ShopDetail>> page(double current, double state) {
        PageParam<ShopDetail> page=new PageParam<ShopDetail>();
        IPage<ShopDetail> shopDetails = shopService.pageAndSortList(page,current,state);
        List<ShopDetail> list = new ArrayList<>();
        Double length = null;
        list = shopDetails.getRecords();
        for (int i = 0; i < list.size(); i++) {
            double c = Double.parseDouble(list.get(i).getShopLat());
            double d = Double.parseDouble(list.get(i).getShopLng());
            length = getDistance(current, state, c, d);
            java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
            String distance;
            if (length < 1) {
                distance = df.format(length * 1000) + "m";

            } else {
                distance = df.format(length) + "km";
            }
            shopDetails.getRecords().get(i).setDistance(distance);
        }
        return ResponseEntity.ok(shopDetails);
    }

    /**
     * 获取官方店铺
     */
    @GetMapping("/authorityShop")
    @PreAuthorize("@pms.hasPermission('shop:shop:authorityShop')")
    public ResponseEntity<ShopDetail> authorityShop(double lat, double lng) {
        ShopDetail shopDetail = shopService.selectAuthorityShop(lat,lng);
        Double length = null;
        double c = Double.parseDouble(shopDetail.getShopLat());
        double d = Double.parseDouble(shopDetail.getShopLng());
        length = getDistance(lat, lng, c, d);
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
        String distance;
        if (length < 1) {
            distance = df.format(length * 1000) + "m";

        } else {
            distance = df.format(length) + "km";
        }
        shopDetail.setDistance(distance);

        return ResponseEntity.ok(shopDetail);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{shopId}")
    @PreAuthorize("@pms.hasPermission('shop:shop:info')")
    public ResponseEntity<ShopDetail> info(@PathVariable("shopId") Long shopId) {
        ShopDetail shopDetail = shopService.getShopDetailByShopId(shopId);
        // 店铺图片
        return ResponseEntity.ok(shopDetail);
    }

    /**
     * 根据店铺id获取店铺所有商品信息
     */
    @GetMapping("/prodInfo/{shopId}")
    @PreAuthorize("@pms.hasPermission('shop:shop:prodInfo')")
    public ResponseEntity<List<Product>> prodInfo(@PathVariable("shopId") Long shopId) {
        List<Product> productList = productService.getProductByShopId(shopId);
        if(CollectionUtils.isNotEmpty(productList)){
            for(Product product:productList){
                Long prodId =  product.getProdId();
                YxPtsp yxPtsp = yxPtspService.getYxPtspbyProdId(prodId);
                if(yxPtsp!=null){
                    product.setIsGroupProd("1");
                }else{
                    product.setIsGroupProd("0");
                }
            }
        }
        return ResponseEntity.ok(productList);
    }

    /**
     * 获取所有的店铺名称
     */
    @GetMapping("/listShopName")
    public ResponseEntity<List<ShopDetail>> listShopName() {
        List<ShopDetail> list = shopService.list().stream().map((dbShopDetail) -> {
            ShopDetail shopDetail = new ShopDetail();
            shopDetail.setShopId(dbShopDetail.getShopId());
            shopDetail.setShopName(dbShopDetail.getShopName());
            return shopDetail;
        }).collect(Collectors.toList());
        return ResponseEntity.ok(list);
    }

    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 通过经纬度获取距离（单位:米）
     */
    public double getDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double radLng1 = rad(lng1);
        double radLng2 = rad(lng2);
        double a = radLat1 - radLat2;
        double b = radLng1 - radLng2;
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        return s;
    }

}
